<template>
  <ekDialog v-model="ekVisiable" title="出库申请" style="width: 70%">
    <div style="padding-right: 20px">
      <div>
        <div
          class="mb-20"
          style="
            color: #999;
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 4px;
          "
          v-if="userList?.length"
        >
          <div class="flex" style="color: #333">
            用户： {{ userList[0].id }}
            <span v-if="userList[0].user_nick"
              >（{{ userList[0].user_nick }}）</span
            >
          </div>
          <div class="flex">
            <div class="f-14 mt-4">总包裹数：{{ orderList?.length || 0 }}</div>
          </div>
        </div>
        <el-divider content-position="left">包含包裹</el-divider>
        <div class="submit-item" v-if="orderList?.length && !loading">
          <el-table ref="table" stripe :data="orderList" max-height="400">
            <el-table-column label="序号" width="60">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="order_logistic_no" label="单号" width="180">
              <template #default="scope">
                {{ scope.row.order_logistic_no }}
              </template>
            </el-table-column>
            <el-table-column
              prop="order_transport_type"
              label="包裹类型"
              width="100"
            >
              <template #default="scope">
                {{ getLable(transportType, scope.row.order_transport_type) }}
              </template>
            </el-table-column>
            <el-table-column label="长宽高（cm）" width="160">
              <template #default="scope">
                {{ scope.row.order_good_length }}*{{
                  scope.row.order_good_width
                }}*{{ scope.row.order_good_height }}
              </template>
            </el-table-column>
            <el-table-column
              prop="proportion_volume"
              label="体积（m³）"
              width="100"
            >
              <template #default="scope">
                {{
                  Number(
                    (scope.row.order_good_length *
                      scope.row.order_good_width *
                      scope.row.order_good_height) /
                      1000000
                  ).toFixed(3)
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="order_good_weight"
              label="重量（kg）"
              width="100"
            >
              <template #default="scope">
                {{ scope.row.order_good_weight }}
              </template>
            </el-table-column>
            <el-table-column prop="order_piece" label="件数" width="60">
              <template #default="scope">
                {{ scope.row.order_piece }}
              </template>
            </el-table-column>
            <el-table-column prop="order_inbound_time" label="入库时间">
              <template #default="scope">
                {{ scope.row.order_inbound_time }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-divider content-position="left">收货信息</el-divider>
        <div>
          <el-form
            ref="forms"
            :model="formData"
            :rules="rules"
            label-width="100px"
          >
            <div class="flex">
              <el-form-item label="姓名" prop="address_name">
                <ekInput v-model="formData.address_name" />
              </el-form-item>
              <el-form-item label="电话" prop="address_phone">
                <ekInput v-model="formData.address_phone" />
              </el-form-item>
            </div>
            <div class="flex" v-if="loaded">
              <el-form-item label="国家" prop="address_country">
                <ekSelectModel
                  :multiple="false"
                  class="w-full"
                  style="width: 200px"
                  v-model="formData.address_country"
                  :name="formData.address_country_model_text"
                  :mapping="{
                    label: ['country_name'],
                    value: 'country_code',
                  }"
                  modelCode="MODEL_COUNTRY"
                />
              </el-form-item>
              <el-form-item label="邮编" prop="address_code">
                <ekInput v-model="formData.address_code" />
              </el-form-item>
            </div>
            <el-form-item label="地址" prop="address_detail">
              <ekTextarea
                v-model="formData.address_detail"
                class="w-full"
                style="width: 200px"
                rows="4"
              />
            </el-form-item>
          </el-form>
          <div v-if="userList?.length" style="margin-left: 30px">
            <el-form-item label="地址选择">
              <ekTableSelect
                style="width: 200px"
                @change="changeAddress"
                :mapping="{
                  label: 'address_name',
                  value: 'id',
                }"
                :layoutData="{
                  modelCode: 'MODEL_ADDRESS',
                  configs: {
                    listUrl:
                      '/business/address/getAddressByUser?authCode=BTN_ORDER_OUTBOUND&userId=' +
                      userList[0].id,
                    treePropsOn: true,
                  },
                  searchs: [],
                  columns: [
                    { type: 'radio' },
                    {
                      label: '姓名',
                      column: 'address_name',
                    },
                    {
                      label: '电话',
                      column: 'address_phone',
                    },
                    {
                      label: '国家',
                      column: 'address_country',
                    },
                    {
                      label: '邮编',
                      column: 'address_code',
                    },
                    {
                      label: '地址',
                      column: 'address_detail',
                    },
                  ],
                }"
              />
            </el-form-item>
          </div>
        </div>
        <el-divider content-position="left">选择快递</el-divider>
        <div class="flex" style="text-align: left; padding-left: 30px">
          <ekRadio v-model="mode" :options="transportMode" @change="getPrice" />
        </div>
        <el-divider content-position="left" v-if="mode">附加费用</el-divider>
        <div class="array-inputs" v-if="mode">
          <template v-if="formData.order_items.length > 0">
            <div
              v-for="(item, index) in formData.order_items"
              :key="index"
              class="array-item"
            >
              <div>
                <div>
                  <span>{{ item.name }}</span>
                  :
                  <span style="color: #f56c6c">{{ item.price }}元 </span>
                </div>
                <div
                  v-if="item.desc"
                  style="color: #999; font-size: 12px; margin-top: 2px"
                >
                  说明： {{ item.desc }}
                </div>
              </div>
              <div style="margin-left: 10px" v-if="item.type == 1">
                <el-radio-group v-model="item.need" size="small" fill="#6cf">
                  <el-radio-button label="需要" value="1" />
                  <el-radio-button label="不需要" value="0" />
                </el-radio-group>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="flex flex-between items-center">
        <div style="margin-left: 20px">
          订单金额：<span
            style="font-size: 24px; color: #f56c6c; font-weight: bold"
            >￥{{ allPrice || "-" }}</span
          >
          <span   style="font-size: 16px; color: #f56c6c; font-weight: bold" v-if="mode" >
            (包含附加费用：￥{{ itemsPrice }})
          </span>
          <span
            @click="showDialog"
            style="cursor: pointer; margin-left: 10px; color: #409eff"
            v-if="mode"
            >查看明细</span
          >
        </div>
        <div style="text-align: right; margin-right: 20px">
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </div>
    </template>
    <el-dialog
      v-model="dialogVisible"
      title="反馈信息"
      width="70%"
      append-to-body
    >
      <div class="dialog-content" style="max-height: 60vh; overflow-y: auto">
        <!-- 反馈信息部分 -->
        <div class="submit-item" v-if="mode">
          <el-divider content-position="left">反馈信息</el-divider>

          <div v-if="costData?.order_plan_list?.length" accordion>
            <OrderFeedback :cost_data="costData"></OrderFeedback>

            <template
              v-for="(item, index) in costData.order_plan_list"
              :key="index"
            >
              <div style="padding: 12px">
                <h4>线路信息{{ index + 1 }}</h4>
                <div class="order-list border-bottom">
                  <div class="order-list-item">
                    <div class="item-box-content">
                      <div class="item-box flex mt-4">
                        <div class="item-box-label">线路计重：</div>
                        <div class="item-box-value font-size-lg">
                          {{ getCost(item) }}
                        </div>
                      </div>

                      <div class="item-box flex x mt-4">
                        <div class="item-box-label">计费方式：</div>
                        <div class="item-box-value font-size-lg">
                          {{ charging[item.charging] }}
                        </div>
                      </div>

                      <div class="item-box flex mt-4">
                        <div class="item-box-label">计费公式：</div>
                        <div class="item-box-value font-size-lg">
                          {{ item.cost_function }}
                        </div>
                      </div>

                      <!-- 体积计费 -->
                      <template v-if="item.charging == 'volume'">
                        <div class="item-box flex mt-4">
                          <div class="item-box-label">计费体积：</div>
                          <div class="item-box-value font-size-lg">
                            {{ item.cost_volume }} m³
                          </div>
                        </div>
                        <div class="item-box flex mt-4">
                          <div class="item-box-label">包裹运费：</div>
                          <div class="item-box-value font-size-lg text-danger">
                            ￥{{ item.price }}
                          </div>
                        </div>
                      </template>

                      <!-- 重量计费 -->
                      <template v-else-if="item.charging == 'quality'">
                        <div class="item-box flex mt-4">
                          <div class="item-box-label">计费重量：</div>
                          <div class="item-box-value font-size-lg">
                            {{ item.cost_weight }}kg
                          </div>
                        </div>
                        <div class="item-box flex mt-4">
                          <div class="item-box-label">包裹运费：</div>
                          <div class="item-box-value font-size-lg text-danger">
                            ￥{{ item.price }}
                          </div>
                        </div>
                      </template>

                      <!-- 其他计费方式 -->
                      <template v-else>
                        <div class="item-box flex mt-4">
                          <div class="item-box-label">计费数量：</div>
                          <div class="item-box-value font-size-lg">
                            {{ item.total_piece }}件
                          </div>
                        </div>

                        <div class="item-box flex mt-4">
                          <div class="item-box-label">包裹运费：</div>
                          <div class="item-box-value font-size-lg text-danger">
                            ￥{{ item.price }}
                          </div>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>

        <!-- 汇总信息部分 -->
        <div class="submit-item" v-if="mode">
          <el-divider content-position="left">汇总</el-divider>
          <div class="order-list">
            <div class="order-list-item">
              <div class="item-box-content">
                <div class="item-box flex" v-if="costData.total_weight > 0">
                  <div class="item-box-label">计费重量：</div>
                  <div class="item-box-value">
                    {{ costData.total_weight }} kg
                  </div>
                </div>

                <div class="item-box flex" v-if="costData.total_volume > 0">
                  <div class="item-box-label">计费体积：</div>
                  <div class="item-box-value">
                    {{ costData.total_volume }} m³
                  </div>
                </div>

                <div class="item-box flex" v-if="costData.total_piece > 0">
                  <div class="item-box-label">计费件数：</div>
                  <div class="item-box-value">
                    {{ costData.total_piece }} 件
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </ekDialog>
</template>

<script setup>
import {
  watch,
  getCurrentInstance,
  computed,
  reactive,
  ref,
  defineEmits,
  onMounted,
} from "vue";
import { apis } from "../data.js";
import ekDialog from "@/components/business/ekDialog/index.vue";
import ekInput from "@/components/form/ekInput/index.vue";
import ekTextarea from "@/components/form/ekTextarea/index.vue";
import ekSelect from "@/components/form/ekSelect/index.vue";
import ekTableSelect from "@/components/form/ekTableSelect/index.vue";
import ekSelectModel from "@/components/form/ekSelectModel/index.vue";
import ekRadio from "@/components/form/ekRadio/index.vue";
import ekUploadImage from "@/components/form/ekUploadImage/index.vue";
import ekTip from "@/components/business/ekTip/index.vue";
import { objectAssignment, getLable } from "@/utils/common.js";
import OrderFeedback from "./OrderFeedback.vue";
import { getDimensionByCode } from "@/utils/sys.js";

const props = defineProps({
  // 显示隐藏
  visiable: {
    type: Boolean,
    default: false,
  },
  rowArr: {
    type: Array,
    default: "",
  },
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http, $ekLoading, $ekMessage, $uploadUrl } =
  globalProperties;

const emit = defineEmits(["update:visiable", "submit"]);

// 是否显示
const ekVisiable = computed({
  get() {
    return props.visiable;
  },
  set(value) {
    emit("update:visiable", value);
  },
});
const outList = computed(() => {
  return props.rowArr;
});
function handleSubmit() {
  let url = apis.outbound;
  forms.value.validate((valid) => {
    if (valid) {
      $http
        .request({
          url: url,
          method: "PUT",
          data: {
            orderIds: outList.value.map((item) => item.id),
            transportMode: mode.value,
            address_name: formData.value.address_name,
            address_phone: formData.value.address_phone,
            address_country: formData.value.address_country,
            address_detail: formData.value.address_detail,
            address_code: formData.value.address_code,
            transfer_items: formData.value.order_items?.length ? formData.value.order_items: '',
          },
        })
        .then((res) => {
          $ekMessage.success(res.message);
          emit("submit");
        })
        .catch((err) => {});
    }
  });
}
const getCost = (item) => {
  if (item.charging == "volume") {
    // 比重
    if (item.proportion_weight > item.total_volume) {
      return "比重（体积重和实重取大值）";
    } else {
      return "实体积";
    }
  }
  if (item.charging == "quality") {
    // 全抛
    if (item.throwing_weight > item.total_weight) {
      return "全抛（体积重和实重取大值）";
    } else {
      return "实重";
    }
  }
  if (item.charging == "piece") {
    return "按件收费";
  }
};
// 对话框可见性
const dialogVisible = ref(false);
// 定义暴露的方法，供父组件调用
const showDialog = () => {
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
};
const loading = ref(false);
let forms = ref(null);
const mode = ref(""); // 运输方式
let formData = ref({
  address_name: "",
  address_phone: "",
  address_country: "",
  address_country_model_text: "",
  address_detail: "",
  address_code: "",
  order_items: [],
});
const initData = () => {
  formData.value = {
    address_name: "",
    address_phone: "",
    address_country: "",
    address_country_model_text: "",
    address_detail: "",
    address_code: "",
    order_items: [],
  };
  mode.value = "";
};

let rules = reactive({
  address_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  address_phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
  address_country: [{ required: true, message: "请输入国家", trigger: "blur" }],
  address_detail: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
  address_code: [{ required: true, message: "请输入邮编", trigger: "blur" }],
});

let orderList = ref([]);
let userList = ref([]);
const transportType = ref({});
const transportMode = ref({});
const payState = ref({});

const charging = {
  volume: "体积",
  quality: "重量",
  piece: "件数",
};

// 初始化表单
async function init() {
  loading.value = true;
  // 详情或者编辑
  let ids = props.rowArr.map((item) => item.id);
  let res = await $http.get(apis.getOrderList, {
    params: {
      ids: ids,
    },
  });
  console.log(res, "ggggggggggggg111111111");
  transportType.value = res.data.type;
  transportMode.value = res.data.mode;
  userList.value = res.data.user_list;
  orderList.value = res.data.order_list;
  formData.value.order_items = res.data.order_items;
  for (let item of formData.value.order_items) {
    item.need = 1;
  }
  loading.value = false;
}

const loaded = ref(false);
watch(
  () => props.visiable,
  async (val) => {
    if (val) {
      initData();
      await init();
      await initItems();
      await getDefaultAddress();
      loaded.value = true;
    }
  }
);
const changeAddress = (data) => {
  console.log(data);
  if (data.length) {
    formData.value = {
      ...formData.value,
      ...data[0],
    };
  }
};
const getDefaultAddress = async () => {
  let user_id = props.rowArr[0].user_id;
  let res = await $http.get(apis.getDefaultAddress, {
    params: {
      user_id: user_id,
    },
  });
  if (res.status == "success") {
    formData.value = {
      ...formData.value,
      ...res.data,
    };
  }
};
const itemsPrice = computed(() => {
  if (!formData.value.order_items?.length) {
    return "0.00";
  }
  return formData.value.order_items
    .filter((item) => item.need == 1)
    .map((item) => item.price)
    .reduce((a, b) => Number(a) + Number(b), 0);
});

const allPrice = computed(() => {
  if (!mode.value) {
    return "0.00";
  }
  let itemsPrice = 0;
  if (formData.value.order_items?.length) {
    itemsPrice = formData.value.order_items
      .filter((item) => item.need == 1)
      .map((item) => item.price)
      .reduce((a, b) => Number(a) + Number(b), 0);
  }
  console.log(itemsPrice, amount.value, "ffffffffffff");
  return (Number(itemsPrice) + Number(amount.value)).toFixed(2);
});
const amount = ref(0);
const priceLoading = ref(false);
const costData = ref({});
const getPrice = async () => {
  priceLoading.value = true;
  const ids = outList.value.map((item) => {
    return item.id;
  });
  let res = await $http.get(apis.getPrice, {
    params: {
      userId: props.rowArr[0].user_id,
      orderIds: ids,
      transportMode: mode.value,
    },
  });
  if (res.status == "success") {
    costData.value = res.data.detail;
    amount.value = Number(res.data.amount);
  }
};
const itemsOption = ref([]);
async function initItems() {
  // 初始化附加项
  $http.get(apis.getItems).then((res) => {
    if (res.status == "success") {
      itemsOption.value = res.data || [];
    }
  });
}
onMounted(async () => {
  let res = await getDimensionByCode("DIM_PAY_STATE");

  payState.value = res.map((item) => ({
    label: item.dimension_name,
    value: item.dimension_code,
  }));
});
</script>
<style scoped lang="scss">
.array-inputs {
  text-align: left;
  margin-left: 40px;
  .array-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    background-color: #f4f4f4;
    padding: 4px;
    border-radius: 4px;
  }
}
</style>
